<?php
/**
 * Created by PhpStorm.
 * 商家商品处理业务
 * User: caicm
 * Date: 2017/6/17
 * Time: 11:30
 */

namespace WMApi\Service;


use WMApi\Model\WmAttrValueModel;
use WMApi\Model\WmCategoryModel;
use WMApi\Model\WmGoodsModel;
use WMApi\Model\WmGoodsSkuModel;
use WMApi\Model\WmStoreCustomizeMenuModel;
use WMApi\Model\WmUnitModel;

class SellerGoodsService {

    /**
     * 商品添加业务
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @param string $goods_name 商品名称
     * @param int $cat_id 分类id
     * @param int $menu_id 菜单id
     * @param int $goods_price 商品价格
     * @param int $unit_id 单位id
     * @param string $goods_img
     * @param int $state 商品状态说明：0：未上架  1：上架 2：下架  3：平台强制下架
     * @param int $sort 排序
     * @param string $describe 描述
     * @param int $goods_weight 商品重量
     * @param array $sku_json
     * @return mixed
     */
    public function add_goods($seller_id=0, $store_id=0, $goods_name='', $cat_id=0, $menu_id=0, $goods_price=0, $unit_id=0, $goods_img='', $state=0, $sort=0, $describe='', $goods_weight=0, $sku_json=array()){

        $unit_model = new WmUnitModel();
        $menu_model = new WmStoreCustomizeMenuModel();
        $cat_model = new WmCategoryModel();
        $goods_model = new WmGoodsModel();
        $sku_model = new WmGoodsSkuModel();

        //验证单位id
        $unit_info = $unit_model->find_unit_info($unit_id);
        if(!$unit_info){
            returnApiError('商品单位参数有误');
        }

        //验证自定义菜单id
        $menu_info = $menu_model->find_menu_info($seller_id, $store_id, $menu_id);
        if(!$menu_info){
            returnApiError('自定义参数有误');
        }

        //二级分类id
        $cat_two_id = $cat_model->get_parent_id($cat_id);
        if(!$cat_two_id){
            returnApiError('请选择第三级分类');
        }

        //一级分类id
        $cat_one_id = $cat_model->get_parent_id($cat_two_id);
        if(!$cat_one_id){
            returnApiError('请选择第三级分类');
        }

        //sku json 处理
        $sku_data = $this->sku_dispose($sku_json);

        if($sku_data){
            $goods_price = $sku_data['min_money'];
            $sku_data = $sku_data['sku_data'];
            $is_sku = 1;

        }else{
            if (!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $goods_price) || !$goods_price) {
                returnApiError('金额有误');
            }
            $sku_data = array(
                array(
                    'goods_money' => $goods_price,
                    'main_attr_id' => 0,
                    'main_attr_name' => '',
                    'main_attr_value_id' => 0,
                    'main_attr_value_name' => '',
                    'sec_attr_id' => 0,
                    'sec_attr_name' => '',
                    'sec_attr_value_id' => 0,
                    'sec_attr_value_name' => ''
                )
            );
            $is_sku = 0;

        }

        $goods_model->startTrans();

        /**
         * 写入商品表
         */
        $add_goods = $goods_model->add_goods($seller_id, $store_id, $goods_name, $cat_id, $cat_two_id, $cat_one_id, $menu_id, $goods_price, $unit_info['unit_id'], $unit_info['unit_name'], $goods_img, $state, $sort, $describe, $is_sku, $goods_weight);

        /**
         * 写入sku表
         */
        $add_sku = $sku_model->add_sku($sku_data, $add_goods);

        if($add_goods && $add_sku){
            $goods_model->commit();
            return $add_goods;
        }else{
            $goods_model->rollback();
            return false;
        }

    }


    /**
     * 商品编辑业务
     * Created By caicm
     * @param int $goods_id 商品id
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @param string $goods_name 商品名称
     * @param int $cat_id 分类id
     * @param int $menu_id 菜单id
     * @param int $goods_price 商品价格
     * @param int $unit_id 单位id
     * @param string $goods_img
     * @param int $state 商品状态说明：0：未上架  1：上架 2：下架  3：平台强制下架
     * @param int $sort 排序
     * @param string $describe 描述
     * @param array $sku_json
     * @param int $goods_weight 商品重量
     * @return mixed
     */
    public function edit_goods($goods_id=0, $seller_id=0, $store_id=0, $goods_name='', $cat_id=0, $menu_id=0, $goods_price=0, $unit_id=0, $goods_img='', $state=0, $sort=0, $describe='', $sku_json=array(), $goods_weight=0){

        $add_sku_state = true;
        $del_sku_state = true;
        $edit_sku_state = true;
        $unit_model = new WmUnitModel();
        $menu_model = new WmStoreCustomizeMenuModel();
        $cat_model = new WmCategoryModel();
        $goods_model = new WmGoodsModel();
        $sku_model = new WmGoodsSkuModel();
        $goods_model->startTrans();

        //验证单位id
        $unit_info = $unit_model->find_unit_info($unit_id);
        if(!$unit_info){
            returnApiError('商品单位参数有误');
        }

        //验证自定义菜单id
        $menu_info = $menu_model->find_menu_info($seller_id, $store_id, $menu_id);
        if(!$menu_info){
            returnApiError('自定义参数有误');
        }

        //二级分类id
        $cat_two_id = $cat_model->get_parent_id($cat_id);
        if(!$cat_two_id){
            returnApiError('请选择第三级分类');
        }

        //一级分类id
        $cat_one_id = $cat_model->get_parent_id($cat_two_id);
        if(!$cat_one_id){
            returnApiError('请选择第三级分类');
        }

        //sku json 处理
        $sku_data = $this->sku_dispose($sku_json);
        if($sku_data){
            $goods_price = $sku_data['min_money'];

            //sku检查分组
            $sku_data = $this->check_sku($sku_data['sku_data'], $goods_id);

            //获取删除数据
            $sku_id = $sku_data['in_sku_id'] ? implode(',', $sku_data['in_sku_id']) : '';
            $del_sku_data = $sku_model->find_del_sku($goods_id, $sku_id);

            /**
             * 删除处理
             */
            if($del_sku_data){
                $sku_id_data = array();
                foreach ($del_sku_data as $value){
                    $sku_id_data[] = $value['sku_id'];
                }
                $del_sku_id = implode(',', $sku_id_data);
                $del_sku_state = $sku_model->del_sku($goods_id, $del_sku_id);
            }

            /**
             * 新增处理
             */
            if($sku_data['new_sku_data']){
                $add_sku_state = $sku_model->add_sku($sku_data['new_sku_data'], $goods_id);
            }

            /**
             * 编辑处理
             */
            if($sku_data['in_sku_data']){
                $edit_sku_state = $sku_model->edit_sku($sku_data['in_sku_data']);
            }
            $is_sku = 1;

        }else{
            if (!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $goods_price) || !$goods_price) {
                returnApiError('金额有误');
            }
            $sku_data = array(
                'goods_money' => $goods_price,
                'main_attr_id' => 0,
                'main_attr_name' => '',
                'main_attr_value_id' => 0,
                'main_attr_value_name' => '',
                'sec_attr_id' => 0,
                'sec_attr_name' => '',
                'sec_attr_value_id' => 0,
                'sec_attr_value_name' => ''
            );

            //获取没规格的sku详情
            $sku_info = $sku_model->find_sku_info($goods_id, 0, 0);
            if($sku_info){

                /**
                 * 编辑 (当前是没规格的sku详情)
                 */
                $sku_data['sku_id'] = $sku_info['sku_id'];
                $edit_sku_state = $sku_model->edit_sku(array($sku_data));

            }else{

                /**
                 * 删除其他sku数据
                 */
                $del_sku_state = $sku_model->del_sku($goods_id);

                /**
                 * 新增sku
                 */
                $add_sku_state = $sku_model->add_sku(array($sku_data), $goods_id);

            }
            $is_sku = 0;

        }

        /**
         * 修改商品表
         */
        $edit_goods_state = $goods_model->edit_goods($goods_id, $seller_id, $store_id, $goods_name, $cat_id, $cat_two_id, $cat_one_id, $menu_id, $goods_price, $unit_info['unit_id'], $unit_info['unit_name'], $goods_img, $state, $sort, $describe, $is_sku, $goods_weight);

        if($edit_sku_state && $add_sku_state && $del_sku_state && $edit_goods_state){
            $goods_model->commit();
            return true;
        }else{
            $goods_model->rollback();
            return false;
        }

    }

    /**
     * sku检查分组
     * @param array $sku_data
     * @param int $goods_id
     * @return array
     */
    protected function check_sku($sku_data=array(), $goods_id=0){

        $sku_model = new WmGoodsSkuModel();
        $new_sku_data = array();
        $in_sku_data = array();
        $in_sku_id = array();

        foreach ($sku_data as $key=>$value){

            //获取sku详情
            $sku_info = $sku_model->find_sku_info($goods_id, $value['main_attr_value_id'], $value['sec_attr_value_id']);
            if($sku_info){
                $value['sku_id'] = $sku_info['sku_id'];
                $in_sku_data[$key] = $value;            //组装已有的数据，用于编辑
                $in_sku_id[] = $sku_info['sku_id'];    //已有的sku_id组，用于删除（已有的sku_id外的sku）
            }else{
                $new_sku_data[$key] = $value; //新增数据
            }
        }

        return array(
            'new_sku_data' => $new_sku_data,
            'in_sku_data' => $in_sku_data,
            'in_sku_id' => $in_sku_id
        );

    }

    /**
     * sku数据处理
     * Created By caicm
     * @param $sku_json
     * @return array|bool
     */
    protected function sku_dispose($sku_json){
        if($sku_json){
            $attr_value_model = new WmAttrValueModel();
            $sku_data = array();
            $money_data = array();

            foreach ($sku_json as $key=>$value){
                $main_attr = array();
                $sec_attr = array();

                if (!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $value['goods_money']) || !$value['goods_money']) {
                    returnApiError('金额有误');
                }

                $sku_data[$key]['goods_money'] = $value['goods_money'];
                $money_data[] = $value['goods_money'];

                //主属性
                if($value['main_attr_value_id']){
                    $main_attr = $attr_value_model->get_attr_info($value['main_attr_value_id']);
                    if($main_attr){
                        $sku_data[$key]['main_attr_id'] = $main_attr['attr_id'];
                        $sku_data[$key]['main_attr_name'] = $main_attr['attr_name'];
                        $sku_data[$key]['main_attr_value_id'] = $main_attr['attr_value_id'];
                        $sku_data[$key]['main_attr_value_name'] = $main_attr['attr_value'];
                    }else{
                        returnApiError('主属性值参数有误');
                    }
                }else{
                    $sku_data[$key]['main_attr_id'] = 0;
                    $sku_data[$key]['main_attr_name'] = '';
                    $sku_data[$key]['main_attr_value_id'] = 0;
                    $sku_data[$key]['main_attr_value_name'] = '';
                }

                //次属性
                if($value['sec_attr_value_id']){
                    $sec_attr = $attr_value_model->get_attr_info($value['sec_attr_value_id']);
                    if($sec_attr){
                        $sku_data[$key]['sec_attr_id'] = $sec_attr['attr_id'];
                        $sku_data[$key]['sec_attr_name'] = $sec_attr['attr_name'];
                        $sku_data[$key]['sec_attr_value_id'] = $sec_attr['attr_value_id'];
                        $sku_data[$key]['sec_attr_value_name'] = $sec_attr['attr_value'];
                    }else{
                        returnApiError('次属性值参数有误');
                    }
                }else{
                    $sku_data[$key]['sec_attr_id'] = 0;
                    $sku_data[$key]['sec_attr_name'] = '';
                    $sku_data[$key]['sec_attr_value_id'] = 0;
                    $sku_data[$key]['sec_attr_value_name'] = '';
                }

            }

            $pos = array_search(min($money_data), $money_data);

            return array(
                'min_money' => $money_data[$pos],
                'sku_data' =>$sku_data
            );

        }else{
            return false;
        }

    }

    /**
     * 获取已添加的商品sku
     * Created By caicm
     * @param int $goods_id
     * @return mixed
     */
    public function get_edit_goods_sku($goods_id=0){

        $sku_model = new WmGoodsSkuModel();
        $sku_list = $sku_model->find_sku_list($goods_id);
        $sku_data = array();
        foreach ($sku_list as $key=>$value){
            $sku_data[] = array(
                'key'=> $value['main_attr_value_id'].'-'.$value['sec_attr_value_id'],
                'val'=>$value['goods_money']
            );
        }

        //主属性
        /*$sku_list = $sku_model->find_main_attr_list($goods_id);
        foreach ($sku_list as $key=>$value){
            $sku_list[$key]['sec_attr_list'] = $sku_model->find_sec_attr_list($goods_id, $value['main_attr_value_id']);
            if($sku_list[$key]['sec_attr_list']){
                unset($sku_list[$key]['goods_money']);
            }
        }

        if($sku_list){
           $sku_data['main_attr_list'] =  $sku_list;
        }else{
            $sku_data['sec_attr_list'] = $sku_model->find_sec_attr_list($goods_id);
        }*/

        return $sku_data;

    }


    /**
     * 获取菜单商品列表
     * Created By caicm
     * @param int $seller_id
     * @param int $store_id
     * @return mixed
     */
    public function get_cat_goods_list($seller_id=0, $store_id=0){
        $menu_model = new WmStoreCustomizeMenuModel();
        $goods_model = new WmGoodsModel();

        //自定义菜单列表
        $menu_list = $menu_model->get_menu_list($seller_id, $store_id, 0);
        foreach ($menu_list as $key=>$value){
            $menu_list[$key]['goods_list'] = $goods_model->find_goodslist_by_menuid($value['menu_id']);
        }

        return $menu_list;

    }

    /**
     * 商品状态修改
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @param int $goods_id 商品id
     * @param int $goods_state 状态 1：上架 2：下架 3:删除
     * @return bool
     */
    public function update_goods_state($seller_id=0, $store_id=0, $goods_id=0, $goods_state=0){
        $goods_model = new WmGoodsModel();
        //商品详情
        $goods_info = $goods_model->find_goods_info($seller_id, $store_id, $goods_id);
        if(!$goods_info){
            returnApiError('商品不存在');
        }
        if($goods_info['is_del'] == 1){
            returnApiError('该商品已删除');
        }
        $state = 0;
        $is_del = 0;
        switch ($goods_state){
            case 1:
                //上架
                if($goods_info['state'] == 3){
                    returnApiError('商品已被平台下架不能上架');
                }
                $state = 1;
                break;
            case 2:
                //下架
                $state = 2;
                break;
            case 3:
                //删除
                if($goods_info['state'] == 1){
                    //returnApiError('上架商品不能直接删除，请先下架在删除');
                }
                $is_del = 1;
                break;
        }

        if($state==0 && $is_del==0){
            return false;
        }

        return $goods_model->update_goods_state($goods_id, $state, $is_del);

    }



}